package com.atguigu.flink.chapter08;

import com.atguigu.flink.bean.AdsClickLog;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.*;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/8/17 15:36
 */
public class Flink04_Project_High_BlackList {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        
        OutputTag<String> black = new OutputTag<String>("black") {};
        
        SingleOutputStreamOperator<String> normal = env
            //.readTextFile("input/AdClickLog.csv")
            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                String[] data = line.split(",");
                return new AdsClickLog(
                    Long.parseLong(data[0]),
                    Long.parseLong(data[1]),
                    data[2],
                    data[3],
                    Long.parseLong(data[4]) * 1000
                );
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<AdsClickLog>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((acl, ts) -> acl.getTimestamp())
            )
            .keyBy(log -> log.getUserId() + "_" + log.getAdsId())
            .process(new KeyedProcessFunction<String, AdsClickLog, String>() {
                
                private ValueState<Boolean> blackListState;
                private ReducingState<Long> clickCountState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    clickCountState = getRuntimeContext()
                        .getReducingState(new ReducingStateDescriptor<Long>("clickCountState", Long::sum, Long.class));
                    
                    blackListState = getRuntimeContext().getState(new ValueStateDescriptor<Boolean>("blackListState", Boolean.class));
                }
    
                @Override
                public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                    clickCountState.clear();
                    blackListState.clear();
                }
    
                @Override
                public void processElement(AdsClickLog value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    // 当出现跨天的时候, 清空状态, 重新计算点击量
                    //1. 使用定时器, 当0点的时候清空状态
                    if (clickCountState.get() == null) {
    
                        if (value.getUserId() == 937166) {
                            System.out.println("跨天....");
                        }
                        
                        long now = ctx.timerService().currentWatermark();
                        LocalDateTime ldt = LocalDateTime.ofEpochSecond(now / 1000, 0, ZoneOffset.ofHours(8));
                        LocalDate localDate = ldt.toLocalDate();
                        LocalDate tomorrow = localDate.plusDays(1);
                        
                        LocalDateTime tomorrowLDT = LocalDateTime.of(tomorrow, LocalTime.of(0, 0, 0));
                        
                        ctx.timerService().registerEventTimeTimer(tomorrowLDT.toEpochSecond(ZoneOffset.ofHours(8)) * 1000);
                    }
                    
                    if (blackListState.value() == null) {
                        clickCountState.add(1L);
                    }
                    // 点击量超过99 并且没有进入黑名单
                    if (clickCountState.get() > 99 && blackListState.value() == null) { // 进入黑名单
                        String msg = ctx.getCurrentKey() + " 点击量: " + clickCountState.get() + "超过阈值, 加入黑名单";
                        ctx.output(black, msg);
                        blackListState.update(true);
                    } else if (clickCountState.get() < 100) {
                        out.collect(ctx.getCurrentKey() + "   " + clickCountState.get() + " 正常点击...");
                    }
                }
            });
        
        normal.print("normal");
        normal.getSideOutput(black).print("black");
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
